import json

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework import serializers

from product.models import Products


# Create your views here.

class TestView(View):
    def get(self, request):
        product_list = Products.objects.all()
        product_dict = product_list.values()
        productList = list(product_dict)
        print(productList)
        return JsonResponse({'code': 200, 'info': '数据查询成功', 'data': productList})


class searchView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        pageNum = data['pageNum']
        pageSize = data['pageSize']
        query = data['query']
        print(pageNum, pageSize)
        # 分页操作
        # productPage = Paginator(Products.objects.all(), pageSize).page(pageNum)
        productPage = Paginator(Products.objects.filter(pname__icontains=query), pageSize).page(pageNum)

        print(productPage)
        productLpage = productPage.object_list.values()
        print(productLpage, type(productLpage))
        productList = list(productLpage)
        # 获取总数据
        total = Products.objects.count()

        return JsonResponse({'code': 200, 'info': '数据查询成功', 'productAll': productList, 'total': total})


class ActionView(View):
    def get(self, request):
        # 根据id 获取商品数据
        id = request.GET.get("id")
        product_obj = Products.objects.get(id=id)

        return JsonResponse({'code': 200, "product": ProductsSerializers(product_obj).data})


class ProductsSerializers(serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = '__all__'
